package com.zmn.oms.task.job.message;

import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.spring.tasktracker.JobRunnerItem;
import com.github.ltsopensource.spring.tasktracker.LTS;
import com.github.ltsopensource.tasktracker.Result;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.oms.business.interfaces.messageV1.SendOrderMessageService;
import com.zmn.oms.manager.utils.TaskConsts;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 类描述：延迟发送 短信/微信 消息
 *
 * @author yule
 * @date 2020/05/07 15:35
 */
@LTS
@Slf4j
public class SendMessageJob {
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    SendOrderMessageService sendOrderMessageService;

    /**
     * 定时发送消息（仅啄木鸟平台）
     *
     * @param job
     * @return
     */
    @JobRunnerItem(shardValue = TaskConsts.TASK_ID_SEND_MESSAGE_JOB)
    public Result sendMessage(Job job) {
        log.info("开始执行任务消息start -->oms_send_message_job--------");
        String orderIdStr = job.getParam("orderId");
        String workIdStr = job.getParam("workId");
        String ruleIdStr = job.getParam("ruleId");
        String nodeMarkStr = job.getParam("nodeMark");

        if (!NumberUtil.isNumber(orderIdStr)) {
            return new Result(Action.EXECUTE_FAILED, "订单号错误!");
        }

        try {
            Long workId = Long.valueOf(workIdStr);
            Long orderId = Long.valueOf(orderIdStr);
            Integer ruleId = Integer.parseInt(ruleIdStr);
            Integer nodeMark = Integer.parseInt(nodeMarkStr);

            log.info("发送消息groupId:[{}],orderId:[{}]", ruleId, orderId);

            OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);

            if (orderWork == null) {
                log.error("#order# 定时发送订单消息，订单不存在");
                return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
            }

            sendOrderMessageService.sendDesignatedRuleIdMessage(orderId, nodeMark, ruleId);

            log.info("发送消息orderId:[{}]的ruleId:[{}]执行完成", ruleId, orderId);

            return new Result(Action.EXECUTE_SUCCESS, "发送消息执行成功了!");
        } catch (Exception e) {
            log.error("发送消息 groupId:[{}],orderId:[{}] 失败:{}", ruleIdStr, orderIdStr, e);
            return new Result(Action.EXECUTE_FAILED, "发送消息失败");
        }
    }
}
